<template>
  <div class="cmsFileTable">
    <el-table
        ref="table"
        :header-cell-style="{
        textAlign: 'center',
        padding: '8px 0',
        backgroundColor: '#f2f2f2',
        borderColor: '#d4d4d4',
      }"
        :cell-style="{ padding: '6px 0', borderColor: '#d4d4d4' }"
        border
        @cell-click="testClick"
        style="width: 100%; margin-bottom: 30px; margin-top: 20px"
        :data="table"
    >
      <el-table-column
          label="序号"
          show-overflow-tooltip
          type="index"
          align="center"
          width="60"
      >
      </el-table-column>
      <el-table-column
          prop="stuffName"
          show-overflow-tooltip
          :label="columnNameArr[0]"
          align="left"
          min-width="190"
      >
      </el-table-column>
      <el-table-column
          prop="fileName"
          label="文件名称"
          align="left"
          min-width="230"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.isMulti">
            <div v-if="scope.row.file[0].realName !== ''" class="pdf">
              <div
                  v-for="(file, index) in scope.row.file"
                  class="pdfItem"
                  :key="file.uid"
              >
                <el-tooltip
                    effect="dark"
                    :content="file.realName"
                    placement="top-start"
                >
                  <div class="pdfBox">
                    <div class="content g-oneLineCut">
                      <img
                          :src="
                          $publicJs.filesTypeFilter(file.realName, '../../../../')
                        "
                          alt=""
                      />
                      <div class="globalTxt ov" @click="checkFile(file, file)">
                        {{ file.realName }}
                      </div>
                    </div>
                    <div class="buttonG">
                      <slot
                          name="innerButton"
                          :row="{ ...scope.row, index: index }"
                      ></slot>
                      <el-button
                          size="mini"
                          v-if="detailType!=='build' && file.id"
                          class="review-detail-table-button"
                          :loading="file.loading"
                          @click="checkFile(file, file)"
                      >查看
                      </el-button>
                      <el-button
                          size="mini"
                          v-if="detailType!=='build' && file.id"
                          class="review-detail-table-button"
                          @click="download(file, scope.row.file, index)"
                      >下载
                      </el-button>
                      <el-button
                          type="danger"
                          size="mini"
                          class="review-detail-table-button"
                          @click="removeFileMul(file, scope.row, index)"
                          v-if="buttonUploadShow(scope.row)"
                      >删除
                      </el-button>
                    </div>
                  </div>
                </el-tooltip>
              </div>
            </div>
            <div v-else style="text-align: center">--</div>
          </div>
          <div v-else>
            <div
                v-if="
                scope.row.file &&
                scope.row.file[0] &&
                scope.row.file[0].realName !== ''
              "
                class="pdf"
                @click="checkFile(scope.row.file[0], scope.row)"
            >
              <img
                  :src="
                  $publicJs.filesTypeFilter(
                    scope.row.file[0].realName,
                    '../../../../'
                  )
                "
                  alt=""
              />
              <div class="globalTxt">{{ scope.row.file[0].realName }}</div>
            </div>
            <div v-else style="text-align: center">--</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="isNeed"
          show-overflow-tooltip
          label="是否必传"
          align="center"
          width="80"
      >
        <template slot-scope="scope">
          <div style="color: red" v-if="scope.row.isNeed">必要</div>
          <div v-else>可选</div>
        </template>
      </el-table-column>
      <el-table-column prop="scheme" label="操作" min-width="120px">
        <template slot-scope="scope">
          <div class="btnGroup">
            <!-- <cmsAssociation v-show="showAssFileBtn(scope.row)"
                            v-if="scope.row.isLink"
                            :project-id="projectId"
                            @select="(val)=>selectAssociation(val, scope.row)"
                            :checked-keys="scope.row.file"/> -->
            <el-upload
                class="upload-demo"
                action=""
                multiple
                v-if="!scope.row.isLink"
                v-show="buttonUploadShow(scope.row)"
                :before-upload="(file) => uploadPartOne(file, scope.row)"
                :show-file-list="false"
                :file-list="scope.row.file"
            >
              <el-button
                  type="primary"
                  size="small"
                  class="review-detail-table-button"
                  :loading="scope.row.loading"
              >
                <span
                    v-if="scope.row.file[0].realName === '' || scope.row.isMulti"
                >上传</span
                >
                <span v-else>更新</span>
              </el-button>
            </el-upload>
            <!--<el-button-->
            <!--size="small"-->
            <!--v-show="buttonCheckShow(scope.row)"-->
            <!--class="review-detail-table-button"-->
            <!--@click="checkFile(scope.row.file[0], scope.row)"-->
            <!--:loading="scope.row.loading||loading"-->
            <!--&gt;查看-->
            <!--</el-button>-->
            <!--<el-button-->
            <!--size="mini"-->
            <!--class="review-detail-table-button"-->
            <!--@click="download(file, scope.row.file)"-->
            <!--v-if="!scope.row.isMulti && scope.row.file[0].realName !== ''"-->
            <!--&gt;下载-->
            <!--</el-button>-->
            <span v-show="showNone(scope.row)"> 暂无文件 </span>
            <el-button
                type="danger"
                size="small"
                v-show="buttonDelShow(scope.row)"
                class="review-detail-table-button"
                @click="removeFileMul(scope.row.file, scope.row)"
                :loading="scope.row.loading"
            >删除
            </el-button>
            <!--            <template slot="button" slot-scope="scope">-->
            <!--            </template>-->
            <slot name="button" :row="scope.row"></slot>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        width="1000px"
        :visible.sync="dialogVisible"
        v-dialog-drag
        title="视频播放"
        append-to-body
        @close="destoryVideo"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
    >
      <div class="flex-hv">
        <video id="videoPlayer" style="width: 100%;" controls :src="videoUrl"></video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {Base64} from 'js-base64'

const PREVIEW_URL = process.env.VUE_APP_FILE_PREVIEW
export default {
  name: 'cmsFileTable',
  props: {
    buildUnitTable: {
      type: Array,
      default: [],
    },
    detailType: {
      type: String,
      default: '',
    },
    detailId: {
      type: Number | String,
      default: '',
    },
    //项目ID，查询关联文件
    projectId: {
      type: String,
      default: '',
    },
    //是否是否加载
    isNeedInit: {
      type: Boolean,
      default: true,
    },
    fileSystem: {
      type: Object,
      default: {
        sys: '',
        module: '',
        entityClass: '',
        viewByAnon: true,
        longLife: false,
      },
    },
    buttonDelShow: {
      type: Function,
      default: () => {
        return false
      },
    },
    showNone: {
      type: Function,
      default: () => {
        return false
      },
    },
    buttonCheckShow: {
      type: Function,
      default: () => {
        return false
      },
    },
    buttonUploadShow: {
      type: Function,
      default: () => {
        return false
      },
    },
    showAssFileBtn: {
      type: Function,
      default: () => {
        return false
      },
    },
    cellClick: {
      type: Function,
      default: () => {
        return false
      },
    },
    columnNameArr: {
      type: Array,
      default: () => {
        return ['材料名称', '文件名称']
      },
    },
  },
  watch: {
    buildUnitTable: {
      handler(val) {
        if (val.length !== this.table.length) {
          if(this.isNeedInit){
            this.$set(this, 'table', [...val])
            if (this.detailType !== 'build') {
              this.init();
            }
          }
        }
        this.$set(this, 'table', [...val])
        //this.init();
      },
      deep: true,
      immediate: true,
    },
    'detailId': {
      handler(val, oldVal) {
        if(this.detailType!=='build'){
          this.init()
        }
      },
      deep: true
    },
    'detailType': {
      handler(val, oldVal) {
        if(this.detailType!=='build'){
          this.init()
        }
      },
      deep: true
    },
  },
  data() {
    return {
      dialogVisible:false,
      videoUrl:'',
      table: [],
      loading:false,
    }
  },
  methods: {
    destoryVideo(){
      $('#videoPlayer').prop('src', '');
    },
    init() {
      for (let i = 0; i < this.table.length; i++) {
        const rows = this.table[i];
        this.$publicUpload.getFile(this.fileSystem.module, this.detailId, rows.part)
            .then(res => {
              const items = res.data || []
              let arr = []
              items.forEach(o => {
                arr.push({
                  realName: o.name,
                  name: o.name,
                  size: o.size,
                  id: o.id
                })
              })
              if(arr.length == 0){
                arr =[
                  { realName: '' }
                ]
              }
              rows.file = arr
              this.change()
            })
      }
    },
    change() {
      this.$emit('change', this.table)
    },
    uploadPartOne(file, row) {
      if(row.hasOwnProperty('canPDF')){
        if(row.canPDF == 'pdf'){
          if(file.name.indexOf('pdf')<0){
            this.$messageWarning('请上传pdf')
            return
          }
        }
      }
      file.realName = file.name
      row.loading = true
      // 在这边可能是需要加入 文件的判断 TODO:
      if (!row.isMulti) {
        row.file = [
          file,
        ]
      } else {
        if (row.file[0].realName === '') {
          row.file = [
            file,
          ]
        } else {
          row.file.push(file)
        }
      }
      row.loading = false
    },
    // 上传文件前
    async beforeUpload(file, ary, part,formid) {
      if(!typeof file || !file.type){
        return ;
      }
      let formId = formid || this.detailId
      if (!formId) {
        this.$messageError('上传文件-表单编号不能为空！')
        return
      }

      /*
       *公共上传方法
       * */
      // ary.loading = true
      const response = await  this.$publicUpload
          .uploadFile(
              file,
              formId,
              this.fileSystem.module,
              part,
              file.name
          )
          .then(async (res) => {
            if (res.code === 200) {
              // 单文件上传前先解绑
              if (ary.file && ary.file[0] && ary.file[0].id && !ary.isMulti) {
                await this.$publicUpload.removeFile(ary.file[0].id)
              }
            } else {
              this.$messageError(res.data.message)
            }
          })
          .catch((res) => {
            this.$messageError(this.$route.name + '上传文件前-请求失败')
          })
          .finally(() => {
            ary.loading = false
          })
      return response
    },
    // 查看文件
    checkFile(file, row) {
      this.$set(row, 'loading', true)
      if(this.detailType !== 'build'){
        if(file.id){

          this.preview(file)
        }
      }
      this.$set(row, 'loading', false)
    },

    preview(row){
      this.videoUrl = ''
      if(row.realName.split('.')[1].indexOf('mp4')>-1||row.realName.split('.')[1].indexOf('avi')>-1){
        this.$set(this,'videoUrl',`${process.env.VUE_APP_BASE_API}/file-server/file/download?id=`+row.id)
        this.$nextTick(()=>{
          this.dialogVisible=true

        })
      }else{
        this.loading = true
        this.$httpGet('/file-server/file/preview?id='+row.id).then(response => {
          this.loading= false;
          //  如果是minio地址路径，则调用kkview
          if(!response.data.startsWith("/")) {
            window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
          }else{
            //  如果是转换后的previewGetFile，浏览器直接打开
            window.open(response.data);
          }
        }).catch(res=>{
          this.loading= false;
        })
      }
    },

    // 获取绑定的附件
    async getFiles() {
      return
    },
    /**
     * 删除文件
     * @param file
     */
    deleteFile(row) {
      this.$confirm(' 此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            if (this.detailType === 'build') {
              row.file = [
                {
                  realName: '',
                },
              ]
              this.$messageSuccess('删除成功')
              return
            }
            //是关联文件的话，就取消关联
            if (row.isLink) {
              this.$publicUpload
                  .unlinkFiles([
                    {
                      sys: 'buss',
                      form: this.detailId,
                      module: this.fileSystem.module,
                      linkModule: row.linkModule,
                      linkPart: row.linkPart,
                      fileId: row.file[0].id,
                    },
                  ])
                  .then((res) => {
                    row.file = [{ realName: '' }]
                    this.$messageSuccess('删除成功')
                  })
              return
            }
            //普通文件删除
            this.$publicUpload.removeFile(row.file[0].id).then((res) => {
              row.file = [
                {
                  realName: '',
                },
              ]
              this.$messageSuccess('删除成功')
            })
          })
          .catch((e) => {
            console.log('delete file e', e)
          })
    },
    removeFileMul(file, row, index = 0) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonClass: 'iconfont icon-icon_ok',
        cancelButtonClass: 'iconfont icon-icon_cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
          .then(async (res) => {
            if (row.isMulti) {
              row.file.forEach((item, index) => {
                if (file.uid === item.uid) {
                  row.file.splice(index, 1)
                  if(row.file.length == 0){
                    this.$set(row, 'file', [{ realName: '' }])
                  }
                }
              })
            }
            if (!row.isMulti) {
              this.$set(row, 'file', [{ realName: '' }])
            }
            if(this.detailType !== 'build' && file.id){
              this.$publicUpload.removeFile(file.id)
            }


            //处理完后触发父组件事件,如果有必要
            this.change()
            this.$messageSuccess('删除成功')
          })
          .catch((e) => {
            console.log('删除文件成功', e)
          })
    },
    download(file, row, index = 0) {
      this.$publicUpload.checkFile(file.id, file.realName)
    },
    async bindAllFile(id) {
      let queue = []
      this.table.forEach((item) => {
        if (
            item.file &&
            item.file[0] &&
            item.file[0].uid&&
            item.file[0].realName != ''
        ) {
          item.file.forEach((fi) => {
            queue.push(this.beforeUpload(fi, item, item.part,id))
          })
        }
      })
      const res  = await Promise.all(queue)
      return res
    },
    testClick(row, column, cell, event) {
      this.cellClick(row, column, cell, event)
    },
  },
}
</script>

<style scoped lang="scss">
.cmsFileTable {
  .pdf {
    display: flex;
    align-items: center;
    justify-content: left;
    cursor: pointer;
    flex-wrap: wrap;

    img {
      display: block;
      height: 20px;
      margin-right: 15px;
    }
  }

  .pdfItem {
    display: flex;
    position: relative;
    justify-content: space-between;
    padding-bottom: 5px;
    align-items: center;

    width: 100%;
    height: 40px;

    .pdfBox {
      padding-top: 5px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      align-items: center;

      .content {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: flex;
        align-items: center;
        flex: 1;
      }
    }

    .buttonG {
      display: flex;
    }
  }

  .btnGroup {
    display: flex;
    align-items: center;
    justify-content: left;
    flex-wrap: wrap;
    padding-top: 5px;

    button {
      margin-left: 10px !important;
      margin-bottom: 5px !important;
    }
  }
}
</style>
